package com.wy.common.tab;

import android.view.View;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import com.wy.w_ui.tab.bottom.WTabBottomInfo;

import java.util.List;


public class WTabViewAdapter {

    private List<WTabBottomInfo<?>> mInfoList;
    private Fragment mCurFragment;
    private FragmentManager mFragmentManager;

    public WTabViewAdapter(FragmentManager fragmentManager,List<WTabBottomInfo<?>> infoList){
        this.mFragmentManager = fragmentManager;
        this.mInfoList = infoList;
    }

    /**
     * 实例化以及显示指定位置的fragment
     * @param container
     * @param position
     */
    public void instantiateItem(View container,int position){

        FragmentTransaction transaction = mFragmentManager.beginTransaction();

        if (mCurFragment != null){
            transaction.hide(mCurFragment);
        }

        String tag = container.getId() + ":" + position;
        Fragment fragment = mFragmentManager.findFragmentByTag(tag);
        if (fragment != null){
            transaction.show(fragment);
        }else {

            fragment = getItem(position);
            if (!fragment.isAdded()){
                transaction.add(container.getId(),fragment,tag);
            }
        }

        mCurFragment = fragment;

        //activity调用了onSaveInstanceState()之后，再commit一个事务就会出现该异常。
        // 那如果不想抛出异常，也可以很简单调用commitAllowingStateLoss()方法来略过这个检查就可以了，
        // 但是这是危险的，如果activity随后需要从它保存的状态中恢复，这个commit是会丢失的
        transaction.commitAllowingStateLoss();
    }

    /**
     * 实例化fragment
     * @param position
     * @return
     */
    public Fragment getItem(int position){
        try {
           return mInfoList.get(position).fragment.newInstance();
        } catch (IllegalAccessException | InstantiationException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取当前Fragment
     * @return
     */
    public Fragment getCurFragment(){
        return mCurFragment;
    }


    /**
     * 获取数量
     * @return
     */
    public int getCount(){
        return mInfoList == null ? 0 : mInfoList.size();
    }
}
